package action;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import model.Orderitem;
import model.Orders;
import model.User;
import service.IOrderService;
import tool.Cart;

import java.sql.Timestamp;
import java.util.Date;
import java.util.Map;

public class orderAction extends ActionSupport {
    private IOrderService orderService;

    public IOrderService getOrderService() {
        return orderService;
    }

    public void setOrderService(IOrderService orderService) {
        this.orderService = orderService;
    }

    public String checkOut() throws Exception {
        Map session = (Map) ActionContext.getContext().getSession();
        Cart cart = (Cart) session.get("cart");
        User user = (User) session.get("user");
        if (user == null) {
            return ERROR;
        }
        Orders order = new Orders();
        order.setOrderdate(new Timestamp(new Date().getTime()));
        order.setUser(user);
        for (Object o : cart.getItems().values()) {
            Orderitem orderitem = (Orderitem) o;
            order.getOrderitems().add(orderitem);
            orderitem.setOrders(order);
        }

        orderService.saveOrder(order);
        Map request = (Map) ActionContext.getContext().get("request");
        request.put("order", order);
        session.remove("cart");
        return SUCCESS;
    }
}
